package org.dizem.util;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties;

/**
 * User: dizem@126.com
 * Time: 11-6-29 下午5:05
 */
public class MailUtil {

	private static final String SMTP_ADDRESS = "smtp.163.com";
	private static final String ADDRESS = "sieg_lu@163.com";
	private static final String PASSWORD = "123654";

	private MailUtil() {
	}

	/**
	 * 发送邮件函数
	 *
	 * @param email 收件地址
	 * @param title 邮件标题
	 * @param content 邮件正文
	 */
	private static void send(String email, String title, String content) {

		Properties p = new Properties();
		p.put("mail.smtp.host", SMTP_ADDRESS);
		p.put("mail.smtp.auth", "true");
		Session s = Session.getInstance(p);

		MimeMessage msg = new MimeMessage(s);
		Transport transport = null;
		try {
			msg.setFrom(new InternetAddress(ADDRESS));
			msg.setRecipient(Message.RecipientType.TO, new InternetAddress(email));
			msg.setText(content);
			msg.setSubject(title);
			msg.setSentDate(new Date());
			msg.saveChanges();

			transport = s.getTransport("smtp");
			transport.connect(SMTP_ADDRESS, ADDRESS, PASSWORD);
			transport.sendMessage(msg, msg.getAllRecipients());


		} catch (AddressException e) {
			e.printStackTrace();
		} catch (MessagingException e) {
			e.printStackTrace();

		} finally {
			try {
				if (transport != null)
					transport.close();
			} catch (MessagingException e) {
				e.printStackTrace();
			}
		}
	}

	public static void sendEmail(String mail, String username, String uid) {
		String content = new StringBuilder().append(username)
				.append(", 您好!\n\n请点击下面的连接完成18团购用户注册\n\n")
				.append("http://localhost:8080/validateEmail?username=")
				.append(username)
				.append("&uid=")
				.append(uid)
				.append("\n\n如果浏览器不能自动打开，请把地址复制到浏览器中手动打开。\n").toString();
		send(mail, "18团购邮箱验证", content);
		System.out.println("send mailto:" + mail + content);
	}
}
